const jwt = require('jsonwebtoken');
const util = require("../lib/util");
const models = require('../models/index');
const config = require('../config/config.json');
const { getUserInfo } = require("../lib/request");
class User {
  // 登录
  static async login(ctx) {
    const { request: { body: user }, app } = ctx;
    user.user_password = util.cryptPwd(user.user_password);
    const result = await models.user.getUser(user.user_name, user.user_password);
    if (!result.data.length) {
      ctx.body = {
        status: false,
        message: "用户名/密码不正确!"
      }
      return
    }
    result.data = result.data[0];
    delete result.data.user_password;
    ctx.state.user = result.data;
    const userInfo = {
      user_name: result.data.user_name,
      id: result.data.id
    }
    const token = jwt.sign(userInfo, config.sign, { expiresIn: '1d' });
    result.data.token = token;
    ctx.body = result;
  }
  // 注册
  static async register(ctx) {
    const { request: { body: user } } = ctx;
    const isExist = await models.user.isExist({
      user_name: user.user_name
    });
    if (isExist.data) {
      ctx.body = {
        status: false,
        message: "用户名已存在!"
      }
      return;
    };
    user.user_password = util.cryptPwd(user.user_password);
    ctx.body = await models.user.insertUser(user);
  }
  // 修改用户资料
  static async edit(ctx) {
    const { params: { id } } = ctx;
    console.log(ctx.user);
    ctx.body = {
      status: true,
      message: "修改成功!"
    };
  }
  // 钉钉登录
  static async dingLogin(ctx) {
    const { request: { body } } = ctx;
    if (!body.code) {
      ctx.body = {
        status: false,
        message: "缺少code字段"
      }
      return
    }
    // 获取用户信息
    let result = JSON.parse(await getUserInfo(body.code));
    if (result.errcode != 0) {
      ctx.body = {
        status: false,
        message: result.errmsg
      }
      return
    }
    // 用户是否已经注册
    let isExist = await models.user.isExist({ unionid: result.unionid });
    if (!isExist.data) {
      let regData = {
        user_name: result.mobile,
        user_password: util.cryptPwd("UU888@asdf"),
        nick: result.name,
        unionid: result.unionid,
        email: result.email
      }
      // 创建用户
      let insertData = await models.user.insertUser(regData);
      regData.id = insertData.insertId;
      delete regData.user_password;
      ctx.state.user = regData;
      let users = {
        user_name: regData.user_name,
        id: regData.id
      }
      regData.token = jwt.sign(users, config.sign, { expiresIn: '1d' });
      ctx.body = {
        status: true,
        data: regData
      }
    } else {
      delete isExist.data.user_password;
      let users = {
        user_name: isExist.data.user_name,
        id: isExist.data.id
      }
      isExist.data.token = jwt.sign(users, config.sign, { expiresIn: '1d' });
      ctx.body = {
        status: true,
        data: isExist.data
      }
    }
  }
}
module.exports = User;